﻿/************************************************************************************
 * @author   wangjian
 *  抓取方式：按住扳机键后，手柄顶部出现一个隐约可见的球体力场），当手柄靠近小车，小车模型和球体接触时，小车被自动吸附到手柄顶端。
在抓取小车的过程中松开扳机键，球体力场消失，小车恢复重力。
************************************************************************************/

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;

public class HandSuckBall : MonoBehaviour {
	Rigidbody handRig;
	public GameObject  suckEffObj;

	public float ThrowThreshold = 10;

	public Rigidbody HandRig{
		get{ return handRig;}
	}
	public bool isGrab = false;

	public CarObjectInteraction grabCarobject = null;

	// Use this for initialization
	void Start () {
		handRig = GetComponent<Rigidbody> ();
	}
	
	// Update is called once per frame
	void Update () {
		if (Input.GetKeyDown (KeyCode.B)) {
			StartSuck ();
		}

		//开始检查靠近手柄的小车模，如果小于规定值则吸入到手柄
		if (isOpenSuck &&( grabCarobject == null)) {
			grabCarobject = GetNearCarObject ();
			if (grabCarobject != null && (grabCarobject.CurrentState == CarShowState.NORMAL) && !isGrab ){
				//
				grabCarobject.GrabCar(this,new CarObjectInteraction.OnGrabComplete(OnGrabCarCallBack));
			}
		}

		if (grabCarobject!=null && grabCarobject.CurrentState== CarShowState.GRABED) {
			if(HandRig.velocity.magnitude>0)
				Debug.LogError ("HandRig.velocity.magnitude: "+HandRig.velocity.magnitude);
			if(HandRig.velocity.magnitude > ThrowThreshold)
				grabCarobject.ThrowCar (HandRig.velocity,handRig.angularVelocity);
		}
	}

	//抓取完成,关闭吸力
	public void OnGrabCarCallBack(){
		isGrab = true;
		CloseSuck ();
	}

	//得到靠近的车模
	public CarObjectInteraction GetNearCarObject(){

		float d = 0;
		CarObjectInteraction o = null;
		foreach (CarObjectInteraction i in ManyCarController.instace.list) {
			float distance = Vector3.Distance (i.transform.position,transform.position);

			if (o == null) {
				d = distance;
				o = i;
			} else {
				if (distance < d) {
					o = i;
					d = distance;
				}
			}


		}
		Debug.LogError ("d: " + d);

		//if(d<0.2f){
			return o;
		//}
		return null;
	}

	public bool isOpenSuck = false;
	//开启吸力
	public void StartSuck(){
		
		suckEffObj.SetActive (true);
		isOpenSuck = true;
	}
	//关闭吸力
	public void CloseSuck(){
		suckEffObj.SetActive (false);
		isOpenSuck = true;
	}



}
